/*
 * Copyright (C) 2009 Teleca Poland Sp. z o.o. <android@teleca.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package small.hero.entertaiment.radio.jiujie.version.zl.activity;

import org.json.JSONException;

import small.hero.entertaiment.radio.jiujie.version.zl.JamendoApplication;
import small.hero.entertaiment.radio.jiujie.version.zl.R;
import small.hero.entertaiment.radio.jiujie.version.zl.adapter.MyRadioAdapter;
import small.hero.entertaiment.radio.jiujie.version.zl.api.Playlist;
import small.hero.entertaiment.radio.jiujie.version.zl.api.Radio;
import small.hero.entertaiment.radio.jiujie.version.zl.api.WSError;
import small.hero.entertaiment.radio.jiujie.version.zl.api.impl.JamendoGet2ApiImpl;
import small.hero.entertaiment.radio.jiujie.version.zl.service.DownloadService;
import small.hero.entertaiment.radio.jiujie.version.zl.service.PlayerService;
import small.hero.entertaiment.radio.jiujie.version.zl.util.Helper;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Process;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Toast;

import com.adview.AdViewLayout;
import com.tools.recommend.NetworkHelper;
import com.waps.AppConnect;

/**
 * Radio navigation activity
 * 
 * @author Lukasz Wisniewski
 */
public class RadioActivity extends Activity {

	/**
	 * statically (don't blame me) inserted recommended radios
	 */
	private static int[] recommended_ids = { 9, // rock
			4, // dance
			5, // hiphop
			6, // jazz
			7, // lounge
			8, // pop
			283 // metal
	};

	/**
	 * Recommended radios
	 */
	private Radio[] mRecommendedRadios;

	/**
	 * Launch this Activity from the outside
	 * 
	 * @param c
	 *            context from which Activity should be started
	 */
	public static void launch(Context c) {
		final Intent intent = new Intent(c, RadioActivity.class);
		c.startActivity(intent);
	}

	private ListView mRadioListView;
	// private RadioAdapter mRadioAdapter;
	private MyRadioAdapter myRadioAdapter;

	// private Button mButton;
	// private EditText mEditText;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.search);

		mRadioListView = (ListView) findViewById(R.id.SearchListView);
		myRadioAdapter = new MyRadioAdapter(this);
		mRadioListView.setOnItemClickListener(mRadioListListener);
		mRadioListView.setAdapter(myRadioAdapter);
		
		// 广告
		final LinearLayout layout = (LinearLayout) findViewById(R.id.adLayout);
		final AdViewLayout adViewLayout = new AdViewLayout(this,
				"SDK20112021530706yz96dgbt4rhgvnd");
		final RelativeLayout.LayoutParams adViewLayoutParams = new RelativeLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		layout.addView(adViewLayout, adViewLayoutParams);
		layout.invalidate();
	}

	private AsyncTask<Void, Void, Playlist> mAsyncTask;
	/**
	 * Launch radio
	 */
	private final OnItemClickListener mRadioListListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			// Radio radio = (Radio) mRadioAdapter.getItem(position);
			final Radio radio = new Radio();
			radio.setId(recommended_ids[position]);

			mAsyncTask = new AsyncTask<Void, Void, Playlist>() {
				private ProgressDialog mDialog;
				Playlist playlist = null;

				@Override
				protected void onPreExecute() {
					mDialog = new ProgressDialog(RadioActivity.this);
					mDialog.setMessage("Please wait while loading...");
					mDialog.setCancelable(true);
					mDialog.setCancelMessage(mHandler.obtainMessage(MSG_CANCEL));
					mDialog.show();
				}

				@Override
				protected Playlist doInBackground(Void... params) {
					if (NetworkHelper.isNetworkAvailable(RadioActivity.this)) {
						try {
							playlist = new JamendoGet2ApiImpl()
									.getRadioPlaylist(radio, 20,
											JamendoApplication.getInstance()
													.getStreamEncoding());

						} catch (final JSONException e) {
							e.printStackTrace();
						} catch (final WSError e) {
							// connection problem or sth/ finish
							mHandler.sendEmptyMessage(MSG_FAIL_GET_CONTENT_FROM_SERVER);
							return null;
						}
					} else {
						mHandler.sendEmptyMessage(MSG_CHECK_NETWORK);
						return null;
					}
					return playlist;
				}

				@Override
				protected void onPostExecute(Playlist result) {
					if (playlist != null) {
						PlayerActivity.launch(RadioActivity.this, playlist);
					} else {

					}
					if (mDialog.isShowing()) {
						try {
							mDialog.dismiss();
						} catch (final Exception e) {
						}
					}
				};

			};
			mAsyncTask.execute();

		}

	};
	private static final int MSG_CANCEL = 123;
	private static final int MSG_CHECK_NETWORK = 124;
	private static final int MSG_FAIL_GET_CONTENT_FROM_SERVER = 125;
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_CANCEL:
				if (mAsyncTask.getStatus() == Status.RUNNING) {
					mAsyncTask.cancel(true);
				}
				break;
			case MSG_MIN:
				finish();
				break;
			case MSG_CHECK_NETWORK:
				Toast.makeText(RadioActivity.this,
						"Please check your network.", Toast.LENGTH_SHORT)
						.show();
				break;
			case MSG_FAIL_GET_CONTENT_FROM_SERVER:
				Toast.makeText(RadioActivity.this,
						"Failed to get data from server.", Toast.LENGTH_SHORT)
						.show();
				break;
			case MSG_EXIT:
				// PlayerService mPlayerService = new PlayerService();
				// mPlayerService.displayNotifycation();
				try {
					// stopService(new Intent(RadioActivity.this,
					// PlayerService.class));
					RadioActivity.this.unbindService(serviceConnection);
					stopService(new Intent(RadioActivity.this,
							DownloadService.class));
				} catch (final Exception e) {
				}
				System.exit(0);
				Process.killProcess(Process.myPid());
				break;
			}
		}

	};
	public static final int MSG_MIN = 202;
	public static final int MSG_EXIT = 203;

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		return super.dispatchKeyEvent(event);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "My Download").setIcon(
				getResources().getDrawable(R.drawable.ic_menu_download));
		menu.add(0, 1, 0, "Share").setIcon(R.drawable.ic_menu_sharel);
		menu.add(0, 2, 0, "More Apps").setIcon(android.R.drawable.ic_menu_more);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			DownloadActivity.launch(RadioActivity.this);
			break;
		case 1:
			Helper.share(RadioActivity.this, null);
			break;
		case 2:
			AppConnect.getInstance(this).showOffers(this);
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private final ServiceConnection serviceConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			countService = (PlayerService) service;
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			countService = null;
		}
	};
	private PlayerService countService;
}
